package com.example.podapp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import podapp.helper.ImageCaptureClass;
import podapp.helper.SignatureGesture;
import InternetServices.WebServiceCall;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class EntryForm extends Activity implements OnItemSelectedListener {

	private ProgressDialog pDialog;
	String RcCode = "", RcRem = "", AwbNo = "", IBCode = "", Result = "",
			Consignee = "", UserId = "";
	String JsonResponse = "", JsonResponseRcRm = "", JsonResponseRcRe;
	Spinner spnpktStatus, spnRCRelation, spnRcRemarks;
	EditText txtRcName, txtRcPhone, txtsignature, txtIBCode;
	Button btnCapturePhoto, btnClearPhoto, btnUpdateData, btnCaptureSignature,
			btnBack;
	ImageView imgphoto, ImgSignature;
	public final String PktStatus_Tag = "PktStatus";
	public final String RcRelation_Tag = "RcRelation";
	public final String RcRmCode_Tag = "RcRemarksCode";
	public final String RcRm_Tag = "RcRemarks";
	List<String> listpktstatus = new ArrayList<String>();
	List<String> listRcRelation = new ArrayList<String>();
	List<String> listRcRemarks = new ArrayList<String>();
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private Uri fileUri;
	Bitmap bitmapImg = null, bitmapSignature = null;
	String base64img = "", base64signature = "";
	boolean isUpdateButtonPressed = false;
	public static final int SIGNATURE_ACTIVITY = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_entry_form);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		GetControls();
		imgphoto = (ImageView) findViewById(R.id.ImgView);
		Intent i = getIntent();
		UserId = i.getSerializableExtra("UserId").toString();
		fillForm(i.getSerializableExtra("JsonData").toString());
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(EntryForm.this, CaseListActivity.class);
				i.putExtra("UserID", UserId);
				startActivity(i);
			}
		});
		btnCapturePhoto = (Button) findViewById(R.id.btnCapturePhoto);
		btnCapturePhoto.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				captureImage();
			}
		});
		//new AsyncWebServiceCall().execute();
		btnUpdateData = (Button) findViewById(R.id.btnUpdateData);
		btnUpdateData.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if (spnpktStatus.getSelectedItemPosition() == 0) {
						if (ValidateEntryForm() == true) {
							base64img = BitmapToBase64StringConvertion(bitmapImg);
							base64signature = BitmapToBase64StringConvertion(bitmapSignature);
							isUpdateButtonPressed = true;
							// new AsyncWebServiceCall().execute();
							if (isUpdateButtonPressed == true) {
								if (SavePodEntry().equalsIgnoreCase("SUCCESS")) {
									AlertDialog.Builder dialog = new AlertDialog.Builder(
											EntryForm.this);
									dialog.setTitle("Message");
									dialog.setMessage("Record Saved Successfully.");
									dialog.setPositiveButton(
											"OK",
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													Intent i = new Intent(
															EntryForm.this,
															CaseListActivity.class);
													i.putExtra("UserID",
															"E1001");
													onStop();
													finish();
													onDestroy();
													startActivity(i);
												}
											});
									dialog.setNegativeButton("Cancel", null);
									dialog.show();
									return;
								}
								else
								{
									Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
								}
								// else
							}
						}
					} else {
						isUpdateButtonPressed = true;
						// new AsyncWebServiceCall().execute();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		btnCaptureSignature = (Button) findViewById(R.id.btnCaptureSignature);
		btnCaptureSignature.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(EntryForm.this,
						SignatureGesture.class);
				startActivityForResult(intent, SIGNATURE_ACTIVITY);
			}
		});
		new AsyncWebServiceCall().execute();
	}

	private void captureImage() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		fileUri = new ImageCaptureClass()
				.getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
		startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// save file url in bundle as it will be null on screen orientation
		// changes
		outState.putParcelable("file_uri", fileUri);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		// get the file url
		fileUri = savedInstanceState.getParcelable("file_uri");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case SIGNATURE_ACTIVITY:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				String status = bundle.getString("status");
				if (status.equalsIgnoreCase("done")) {
					ImageView image = (ImageView) findViewById(R.id.ImgSignature);
					ByteArrayInputStream imageStreamClient = new ByteArrayInputStream(
							data.getExtras().getByteArray("draw"));
					image.setImageBitmap(BitmapFactory
							.decodeStream(imageStreamClient));
					image.setBackgroundResource(R.drawable.imageborder);
					byte[] b1 = data.getExtras().getByteArray("draw");
					Bitmap bitmap = BitmapFactory.decodeByteArray(b1, 0,
							b1.length);
					bitmapSignature = bitmap;
				}
			}
			break;
		}

		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				ShowMessage("User cancelled image capture");
			} else {
				ShowMessage("User cancelled image capture");
			}
		}

	}

	private void previewCapturedImage() {
		try {
			imgphoto.setVisibility(View.VISIBLE);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 8;
			bitmapImg = BitmapFactory.decodeFile(fileUri.getPath(), options);
			imgphoto.setImageBitmap(bitmapImg);
			imgphoto.setBackgroundResource(R.drawable.imageborder);
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	public class AsyncWebServiceCall extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(EntryForm.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			WebServiceCall webObj = new WebServiceCall();
			/*
			 * if (isUpdateButtonPressed == true) { SavePodEntry(); }
			 */// else {
			JsonResponse = webObj.webServiceMethod("GetPacketStatus",
					new Hashtable<String, String>());
			JsonResponseRcRe = webObj.webServiceMethod("GetRcRelation",
					new Hashtable<String, String>());
			JsonResponseRcRm = webObj.webServiceMethod("GetRemarks",
					new Hashtable<String, String>());
			bindSpinner(listpktstatus, JsonResponse, PktStatus_Tag, "");
			bindSpinner(listRcRelation, JsonResponseRcRe, RcRelation_Tag, "");
			bindSpinner(listRcRemarks, JsonResponseRcRm, RcRmCode_Tag, RcRm_Tag);
			// }
			return null;
		}

		// common function to bind spinner items
		public void bindSpinner(List<String> SpinnerList, String JsonResult,
				String Tag1, String Tag2) {
			if (JsonResult != "") {
				String Tag1Str = "", Tag2Str = "";
				boolean flag = false;
				JSONObject jsonObj = null;
				try {
					jsonObj = new JSONObject(JsonResult);
					JSONArray jsonArr = jsonObj.getJSONArray("Result");
					for (int i = 0; i < jsonArr.length(); i++) {
						JSONObject jsonInner = jsonArr.getJSONObject(i);
						Tag1Str = jsonInner.getString(Tag1);
						if (jsonInner.has(Tag2)) {
							flag = true;
							Tag2Str = jsonInner.getString(Tag2);
						}
						if (flag == true) {
							SpinnerList.add(Tag1Str + " : " + Tag2Str);
						} else {
							SpinnerList.add(Tag1Str);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		@Override
		protected void onPostExecute(Void result) {
			if (pDialog.isShowing())
				pDialog.dismiss();
			spnpktStatus = (Spinner) findViewById(R.id.spnPktStatus);
			spnRCRelation = (Spinner) findViewById(R.id.spnRCRelation);
			spnRcRemarks = (Spinner) findViewById(R.id.spnRCReamrks);
			spnpktStatus.setOnItemSelectedListener(EntryForm.this);
			// Creating adapter for spinner default
			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
					EntryForm.this, android.R.layout.simple_spinner_item,
					listpktstatus);
			ArrayAdapter<String> dataAdapterRcRe = new ArrayAdapter<String>(
					EntryForm.this, android.R.layout.simple_spinner_item,
					listRcRelation);
			ArrayAdapter<String> dataAdapterRcRm = new ArrayAdapter<String>(
					EntryForm.this, android.R.layout.simple_spinner_item,
					listRcRemarks);
			dataAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			dataAdapterRcRe
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			dataAdapterRcRm
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spnpktStatus.setAdapter(dataAdapter);
			spnRCRelation.setAdapter(dataAdapterRcRe);
			if (!dataAdapterRcRe.isEmpty())
				spnRCRelation.setSelection(12);
			spnRcRemarks.setAdapter(dataAdapterRcRm);
			spnRcRemarks.setVisibility(View.GONE);
			/*
			 * if (Result.equalsIgnoreCase("SUCCESS")) { Intent intent = new
			 * Intent(EntryForm.this, CaseListActivity.class);
			 * startActivity(intent); }
			 */
			spnRCRelation
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
							// TODO Auto-generated method stub
							if (spnRCRelation.getSelectedItem().toString()
									.equalsIgnoreCase("SELF")) {
								// txtRcName.setVisibility(view.GONE);
								txtRcName.setText(Consignee);
							} else {
								// txtRcName.setVisibility(view.VISIBLE);
								txtRcName.setText("");
							}

						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							// TODO Auto-generated method stub

						}
					});

		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		String item = parent.getItemAtPosition(position).toString();
		if (!item.equalsIgnoreCase("DLVRD")) {
			spnRcRemarks.setVisibility(View.VISIBLE);
			spnRCRelation.setVisibility(View.GONE);
			GetControls();
			hide_UnhideControls(false);
		} else {
			spnRcRemarks.setVisibility(View.GONE);
			spnRCRelation.setVisibility(View.VISIBLE);
			GetControls();
			hide_UnhideControls(true);
		}
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}

	public void hide_UnhideControls(boolean flag) {
		int val = View.VISIBLE;
		if (flag == false) {
			val = View.GONE;
		} else {
			val = View.VISIBLE;
		}
		txtRcName.setVisibility(val);
		txtRcPhone.setVisibility(val);
		imgphoto.setVisibility(val);
		btnCaptureSignature.setVisibility(val);
		btnCapturePhoto.setVisibility(val);
		ImgSignature.setVisibility(val);
	}

	public void GetControls() {
		txtRcName = (EditText) findViewById(R.id.txtRCName);
		txtRcPhone = (EditText) findViewById(R.id.txtRCPhone);
		txtIBCode = (EditText) findViewById(R.id.txtIBCode);
		imgphoto = (ImageView) findViewById(R.id.ImgView);
		btnCapturePhoto = (Button) findViewById(R.id.btnCapturePhoto);
		btnCaptureSignature = (Button) findViewById(R.id.btnCaptureSignature);
		ImgSignature = (ImageView) findViewById(R.id.ImgSignature);

	}

	public void fillForm(String Data) {
		try {
			if (Data != "") {
				JSONArray jsonArr = new JSONArray(Data);
				String IBCode = "";
				Consignee = "";
				for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					if (jsonObj != null) {
						IBCode += jsonObj.getString("IBCode");
						Consignee = jsonObj.getString("Consignee");
						AwbNo += jsonObj.getString("AwbNo");
						if (jsonArr.length() - 1 != i) {
							IBCode += ",";
							AwbNo += ",";
						}
					}
				}
				EditText txtConsignee = (EditText) findViewById(R.id.txtConsignee);
				txtIBCode.setText(IBCode + ",");
				txtConsignee.setText(Consignee);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String BitmapToBase64StringConvertion(Bitmap myBitmap) {
		String base64Result;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		myBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		byte[] data = baos.toByteArray();
		base64Result = Base64.encodeToString(data, 0);
		return base64Result;
	}

	// Method to validate form
	public boolean ValidateEntryForm() {
		boolean flag = true;
		if (spnpktStatus.getSelectedItemPosition() == 0) {
			if (txtRcName.getText().toString().trim().equalsIgnoreCase("")) {
				txtRcName.requestFocus();
				ShowMessage("Please Enter RcName.");
				return false;
			}
			if (txtRcPhone.getText().toString().trim().equalsIgnoreCase("")) {
				txtRcPhone.requestFocus();
				ShowMessage("Please Enter RcPhone.");
				return false;
			}
			if (bitmapImg == null) {
				ShowMessage("Please capture photo.");
				return false;
			}
			if (bitmapSignature == null) {
				ShowMessage("Please take signature.");
				return false;
			}
		}

		return flag;
	}

	public String SavePodEntry() {
		boolean flag = false;
		String Status = "";
		WebServiceCall webObj = new WebServiceCall();
		try {
			if (spnpktStatus.getSelectedItemPosition() == 0) {
				if (ValidateEntryForm() == true) {
					Map<String, String> map = new Hashtable<String, String>();
					map.put("SignaturePic", base64signature);
					map.put("PodPic", base64img);
					map.put("AwbNoList", txtIBCode.getText().toString());
					map.put("RcName", txtRcName.getText().toString().trim());
					map.put("RcPhone", txtRcPhone.getText().toString().trim());
					map.put("RcRelation", spnRCRelation.getSelectedItem()
							.toString());
					map.put("PktStatus", spnpktStatus.getSelectedItem()
							.toString());
					map.put("RcRemarks", "");
					map.put("IMEINo", getDeviceId());
					SaveResult(webObj.webServiceMethod("SavePOD", map));
				} else {
					ShowMessage("Error in filling form");
				}
			} else {
				Map<String, String> map = new Hashtable<String, String>();
				map.put("SignaturePic", "");
				map.put("PodPic", "");
				map.put("AwbNoList", txtIBCode.getText().toString());
				map.put("RcName", "");
				map.put("RcPhone", "");
				map.put("RcRelation", "");
				map.put("PktStatus", spnpktStatus.getSelectedItem().toString());
				map.put("RcRemarks", spnRcRemarks.getSelectedItem().toString());
				map.put("IMEINo", getDeviceId());
				Status = SaveResult(webObj.webServiceMethod("SavePOD", map));
			}
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}

		return Status;
	}

	public String SaveResult(String resultData) {
		try {
			JSONObject jsonObj = new JSONObject(resultData);
			JSONArray jsonArr = jsonObj.getJSONArray("Result");
			for (int i = 0; i < jsonArr.length(); i++) {
				JSONObject jsonNode = jsonArr.getJSONObject(i);
				Result = jsonNode.getString("feed");
			}

		} catch (Exception e) {

		}
		return Result;
	}

	public String getDeviceId() {
		String IMEINo = "";
		try {
			TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			IMEINo = telephonyManager.getDeviceId();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return IMEINo;
	}

	public void ShowMessage(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}
}
